import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/point_exchange_account.dart';
import 'package:mall/core/models/point_exchange_history_res.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/point/components/point_type_in_sheet.dart';
import 'package:mall/screens/point/components/point_type_out_sheet.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 兑换历史
class PointHistroyScreen extends StatefulWidget {
  static const routeName = '/PointHistroyScreen';

  @override
  _PointHistroyScreenState createState() => _PointHistroyScreenState();
}

class _PointHistroyScreenState extends State<PointHistroyScreen> {
  final DateFormat _dateFormat = DateFormat("yyyy-MM-dd");
  PointExchangeAccount _typeIn;
  PointExchangeAccount _typeOut;
  DateTime _startTime;
  DateTime _endTime;
  RefreshController _refreshController;
  int _pageIndex;
  final _list = List<PointExchangeHistoryRes>();

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: true);
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("兑换历史"),
      ),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.all(8.w),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        child: OutlineButton(
                          onPressed: _pointExchangeTypeIn,
                          child: Text(_typeIn?.name ?? "兑入账户"),
                        ),
                      ),
                    ),
                    Text(" - "),
                    Expanded(
                      child: Container(
                        child: OutlineButton(
                          onPressed: _pointExchangeTypeOut,
                          child: Text(_typeOut?.name ?? "兑出账户"),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 8.w,
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        child: OutlineButton(
                          onPressed: () {
                            DatePicker.showDatePicker(
                              context,
                              maxTime: _endTime,
                              onConfirm: (value) {
                                setState(() {
                                  _startTime = value;
                                });
                              },
                              locale: LocaleType.zh,
                            );
                          },
                          child: Text(
                            _startTime == null ? "起始日期" : _dateFormat.format(_startTime),
                          ),
                        ),
                      ),
                    ),
                    Text(" - "),
                    Expanded(
                      child: Container(
                        child: OutlineButton(
                          onPressed: () {
                            DatePicker.showDatePicker(
                              context,
                              minTime: _startTime,
                              onConfirm: (value) {
                                setState(() {
                                  _endTime = value;
                                });
                              },
                              locale: LocaleType.zh,
                            );
                          },
                          child: Text(
                            _endTime == null ? "截止日期" : _dateFormat.format(_endTime),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 8.w,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    SizedBox(
                      height: 32.w,
                      child: OutlineButton(
                        onPressed: () {
                          // 清除条件
                          setState(() {
                            _typeIn = null;
                            _typeOut = null;
                            _startTime = null;
                            _endTime = null;
                          });
                        },
                        child: Text("清除条件"),
                      ),
                    ),
                    SizedBox(
                      width: 8.w,
                    ),
                    SizedBox(
                      height: 32.w,
                      child: RaisedButton(
                        onPressed: () {
                          _refreshController.requestRefresh();
                        },
                        child: Text("查询"),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              child: ListView.separated(
                padding: EdgeInsets.symmetric(
                  vertical: 8.w,
                ),
                itemBuilder: (context, index) {
                  return PointExchangeHistoryItem(
                    res: _list[index],
                  );
                },
                separatorBuilder: (context, index) {
                  return SizedBox(
                    height: 8.w,
                  );
                },
                itemCount: _list.length,
              ),
              enablePullUp: _list.length % 10 == 0,
              onRefresh: _onRefresh,
              onLoading: _onLoading,
            ),
          ),
        ],
      ),
    );
  }

  /// 兑入账户
  void _pointExchangeTypeIn() async {
    final typeIn = await showModalBottomSheet<PointExchangeAccount>(
      context: context,
      builder: (context) {
        return PointTypeInSheet(
          displayBalance: false,
        );
      },
    );
    if (typeIn != null) {
      setState(() {
        _typeIn = typeIn;
      });
    }
  }

  /// 兑出账户
  void _pointExchangeTypeOut() async {
    if (_typeIn == null) {
      EasyLoading.showToast("请先选择兑入账户");
      return;
    }
    final typeOut = await showModalBottomSheet<PointExchangeAccount>(
      context: context,
      builder: (context) {
        return PointTypeOutSheet(
          inAccountType: _typeIn.accountType,
          displayBalance: false,
        );
      },
    );
    if (typeOut != null) {
      setState(() {
        _typeOut = typeOut;
      });
    }
  }

  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<Api>();
    try {
      final list = await api.pointExchangeHistory(
        _typeIn?.accountType,
        _typeOut?.accountType,
        _startTime,
        _endTime,
        _pageIndex,
      );
      if (!mounted) {
        return;
      }
      setState(() {
        _list.clear();
        _list.addAll(list);
      });
      _refreshController.refreshCompleted();
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
      _refreshController.refreshFailed();
    }
  }

  void _onLoading() async {
    _pageIndex++;
    final api = context.read<Api>();
    try {
      final list = await api.pointExchangeHistory(
        _typeIn?.accountType,
        _typeOut?.accountType,
        _startTime,
        _endTime,
        _pageIndex,
      );
      if (!mounted) {
        return;
      }
      setState(() {
        _list.addAll(list);
      });
      _refreshController.loadComplete();
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
      _refreshController.loadFailed();
    }
  }
}

class PointExchangeHistoryItem extends StatelessWidget {
  const PointExchangeHistoryItem({
    Key key,
    @required this.res,
  }) : super(key: key);

  final PointExchangeHistoryRes res;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.w),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding: EdgeInsets.symmetric(
                  horizontal: 4.w,
                ),
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.grey,
                  ),
                ),
                child: Text(
                  "${res.id}",
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 12,
                  ),
                ),
              ),
              Text(
                " ${res.inAmount}",
                style: TextStyle(
                  color: res.inAmount.startsWith("-") ? Colors.green : Colors.red,
                  fontSize: 18,
                ),
              ),
              Text(" (${res.inAccountTypeName})"),
              Spacer(),
              Text(
                " ${res.outAmount}",
                style: TextStyle(
                  color: res.outAmount.startsWith("-") ? Colors.green : Colors.red,
                  fontSize: 18,
                ),
              ),
              Text(" (${res.outAccountTypeName})"),
            ],
          ),
          SizedBox(
            height: 8,
          ),
          Text(
            "${res.note}",
            style: TextStyle(
              color: Colors.grey[600],
            ),
          ),
          SizedBox(
            height: 8.w,
          ),
          Text(
            "${res.createTime}",
            style: TextStyle(
              color: Colors.grey,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }
}
